import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/utils/http.dart';
import 'package:flutter_enjoy_plus/utils/logger.dart';
import 'package:flutter_enjoy_plus/utils/toast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  String baseUrl = 'https://restapi.amap.com/v3';
  String key = '562b98be5213fb0455e1aea4d94248bc';
  String address = '';
  List communitiesList = [];

  @override
  void initState() {
    // 获取位置授权
    requestLocationPermission();
    // 模拟地址逆地址解析
    reverseGeoCoding(121.618684, 31.040295);
    // 获取周边社区
    queryNearbyCommunities(121.618684, 31.040295);
    super.initState();
  }

// 获取位置权限
  requestLocationPermission() async {
    if (await Permission.location.request().isGranted) {
      // 是否已授权
      ToastUtil.showSuccess('已授权');
      getCurrentLocation();
    } else {
      ToastUtil.showSuccess('未授权');
    }
  }

// 获取当前坐标（经纬度）
  getCurrentLocation() async {
    late LocationSettings locationSettings;

    if (defaultTargetPlatform == TargetPlatform.android) {
      locationSettings = AndroidSettings(
          accuracy: LocationAccuracy.high,
          distanceFilter: 100,
          forceLocationManager: true,
          intervalDuration: const Duration(seconds: 10),
          //(Optional) Set foreground notification config to keep the app alive
          //when going to the background
          foregroundNotificationConfig: const ForegroundNotificationConfig(
            notificationText:
                "Example app will continue to receive your location even when you aren't using it",
            notificationTitle: "Running in Background",
            enableWakeLock: true,
          ));
    } else if (defaultTargetPlatform == TargetPlatform.iOS ||
        defaultTargetPlatform == TargetPlatform.macOS) {
      locationSettings = AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.fitness,
        distanceFilter: 100,
        pauseLocationUpdatesAutomatically: true,
        // Only set to true if our app will be started up in the background.
        showBackgroundLocationIndicator: false,
      );
    } else if (kIsWeb) {
      locationSettings = WebSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        // 5分钟后，更新定位
        maximumAge: Duration(minutes: 5),
      );
    } else {
      locationSettings = LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
      );
    }

    try {
      // supply location settings to getCurrentPosition
      Position position = await Geolocator.getCurrentPosition(
          locationSettings: locationSettings);
      ToastUtil.showSuccess('获取地理位置成功');
      ToastUtil.showInfo('纬度${position.latitude} - 经度${position.longitude}');
      // 由于模拟器定位在国外，高德地图无法获取详细地址。因此模拟一个国内地址
      // 121.618684,31.040295
      reverseGeoCoding(121.618684, 31.040295);
    } catch (e) {
      ToastUtil.showSuccess('获取地理位置失败');
    }
  }

// 根据坐标，获取详细地址。逆地址解析
  reverseGeoCoding(double longitude, double latitude) async {
    try {
      // v3/geocode/regeo?key=您的key&location=116.481488,39.990464
      final url =
          '$baseUrl/geocode/regeo?key=$key&location=$longitude,$latitude';
      final res = await http.get(url);
      // logger.i(res);
      // ToastUtil.showSuccess(res['regeocode']['formatted_address']);
      setState(() {
        address = res['regeocode']['formatted_address'];
      });
    } catch (e) {
      ToastUtil.showError('地址获取失败');
    }
  }

  // 获取POI（point of interest）,周边社区
  queryNearbyCommunities(double longitude, double latitude) async {
    final url = '$baseUrl/place/around?key=$key&location=$longitude,$latitude';
    final res = await http.get(url);
    try {
      res['pois'];
      // logger.i(res['pois']);
      // 只需要每个数组中的name
      for (var element in res['pois']) {
        // logger.i(element['name']);
        setState(() {
          communitiesList.add(element['name']);
          // logger.i(communitiesList);
        });
      }
    } catch (e) {
      ToastUtil.showError('获取周边社区失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('选择社区'),
        ),
        body: ListView(
          padding: const EdgeInsets.all(10),
          children: [
            const Row(
              children: [
                Text(
                  '当前地址',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.all(10),
              child: Row(
                children: [
                  Expanded(child: Text(address)),
                  const Row(
                    children: [
                      Icon(Icons.location_searching_outlined,
                          color: Colors.blue),
                      SizedBox(width: 2),
                      Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ],
                  )
                ],
              ),
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '附近社区',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            ListView(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                children: communitiesList.map((item) {
                  return Container(
                      color: Colors.white,
                      padding: const EdgeInsets.all(10),
                      child: Row(children: [
                        Expanded(child: Text(item)),
                        const Row(children: [
                          Icon(Icons.arrow_forward_ios,
                              size: 16, color: Colors.black),
                        ])
                      ]));
                }).toList())
          ],
        ));
  }
}
